import { request, RequestOptions } from '@/utils/http';
import { v4 as uuidv4 } from '@/utils/guid';

/**
 * 模型树节点接口
 */
export interface ModelTreeNode {
  FMID: string;
  FPID: string;
  FTNID: string;
  FNAME: string;
  FSTATE: number;
  children?: ModelTreeNode[];
}

/**
 * 模型详情接口
 */
export interface ModelDetail {
  FMID: string;
  FPID: string;
  FFID: number;
  FTNID: string;
  FCODE: string;
  FNAME: string;
  FSHORT_NAME: string;
  FSTATE: number;
  FTYPE: string;
  FADD_USER: string;
  FADD_TIME: string;
  FLAST_USER: string;
  FLAST_TIME: string | null;
  FMEMO: string;
  FLASTMODIFIED: string;
  FEXPLAIN: string;
  FBIZ_CATEGORY: string;
  FTABLE_NAME: string;
  FCMD_QUERY: string;
  FCMD_EXECUTE: string;
}

/**
 * API 响应接口
 */
interface ApiResponse<T> {
  metaid: string;
  rows: T[];
}

/**
 * 获取模型树数据
 * @param tnid 租户ID，默认为 "*"
 */
export function getModelTree(tnid: string = '*') {
  return request<ApiResponse<ModelTreeNode>[]>({
    metaid: '{_plat.cfgmeta.tree_}',
    table: 'TPLAT_CFGMETA',
    caption: '模型树',
    kind: 'query',
    edit: [],
    execute: [],
    query: {
      data: {
        FTNID: tnid,
        FREQID: uuidv4(),
      },
    },
  });
}

/**
 * 获取单个模型详情
 * @param fmid 模型ID
 */
export function getModelDetail(fmid: string) {
  return request<ApiResponse<ModelDetail>[]>({
    metaid: '{_plat.cfgmeta.one_}',
    table: 'TPLAT_CFGMETA',
    caption: '模型维护',
    kind: 'query',
    edit: [],
    execute: [],
    query: {
      data: {
        FMID: fmid,
        FREQID: uuidv4(),
      },
    },
  });
}

/**
 * 新增模型
 * @param data 模型数据
 */
export function createModel(data: Partial<ModelDetail>) {
  return request({
    metaid: '{_plat.cfgmeta.one_}',
    table: 'TPLAT_CFGMETA',
    caption: '模型维护',
    kind: 'edit',
    edit: [
      {
        action: 'INSERT',
        data: {
          ...data,
          FREQID: uuidv4(),
        },
      },
    ],
    execute: [],
    query: {},
  });
}

/**
 * 修改模型
 * @param data 模型数据
 */
export function updateModel(data: Partial<ModelDetail>) {
  return request({
    metaid: '{_plat.cfgmeta.one_}',
    table: 'TPLAT_CFGMETA',
    caption: '模型维护',
    kind: 'edit',
    edit: [
      {
        action: 'UPDATE',
        data: {
          ...data,
          FREQID: uuidv4(),
        },
      },
    ],
    execute: [],
    query: {},
  });
}

/**
 * 删除模型
 * @param fmid 模型ID
 * @param tnid 租户ID
 */
export function deleteModel(fmid: string, tnid: string) {
  return request({
    metaid: '{_plat.cfgmeta.one_}',
    table: 'TPLAT_CFGMETA',
    caption: '模型维护',
    kind: 'edit',
    edit: [
      {
        action: 'DELETE',
        data: {
          FMID: fmid,
          FTNID: tnid,
          FREQID: uuidv4(),
        },
      },
    ],
    execute: [],
    query: {},
  });
}
